package com.example.imitation_webchat_demo.util;

import java.security.KeyStore;

import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;

import android.content.Context;
import android.util.Log;

public class HttpUtils {
	public static HttpClient getNewHttpClient(Context context) {
		try {
			// 需要特定证书的
//			KeyStore keyStore = KeyStore.getInstance("BKS");
//			InputStream is = context.getAssets().open("server_trust.keystore");
//			keyStore.load(is, "360702".toCharArray());
			
			// 信任所有证书的
			KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
			keyStore.load(null, null);

			SSLSocketFactory sf = new EasySSLSocketFactory(keyStore); 
			sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
			
			HttpParams params = new BasicHttpParams();
			HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
			HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); 

			SchemeRegistry registry = new SchemeRegistry();
//			registry.register(new Scheme("http", PlainSocketFactory
//					.getSocketFactory(), 180));
			registry.register(new Scheme("https", sf, 18443));

			ClientConnectionManager ccm = new ThreadSafeClientConnManager(
					params, registry);
			HttpClient client = new DefaultHttpClient(ccm, params); 
			return client;
		} catch (Exception e) {
			e.printStackTrace();
			Log.e("HttpUtils", "exception");
			return new DefaultHttpClient();
		}
	}
}